<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <el-row :gutter="20">
        <el-col :span="12">宠物知识管理</el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="showAddDrawer">添加文章</el-button>
        </el-col>
      </el-row>
    </template>

    <!-- 搜索栏 -->
    <div>
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="文章标签">
          <el-select v-model="searchForm.tag" default-first-option filterable @change="handleSearch"
            style="min-width: 120px;">
            <el-option label="全部" value="全部"></el-option>
            <el-option v-for="category in categories" :key="category" :label="category" :value="category"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="搜索标题">
          <el-input v-model="searchForm.search_title" placeholder="请输入标题关键字" @keyup.enter="handleSearch"></el-input>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" @change="handleSearch"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 文章表格 -->
      <el-table :data="articles" v-loading="loading" style="width: 100%">
        <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="文章标题" prop="title" min-width="200">
          <template #default="{ row }">
            <div class="article-title">{{ row.title }}</div>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="column" width="120"></el-table-column>
        <el-table-column label="发表时间" prop="view_date" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="PAGE_SIZE"
        :total="totalArticles"></el-pagination>
    </div>

    <!-- 文章发表抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="50%" direction="rtl">
      <AddArticleSet v-if="dialogType === 'add'" @cancel="handleCancel" />
      <EditArticleSet v-if="dialogType === 'edit'" :articleData="currentArticle" @cancel="handleCancel" />
    </el-drawer>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddArticleSet from '@/views/Page/addArticleSet.vue';
import EditArticleSet from '@/views/Page/editArticleSet.vue';
import { getArticles, deleteArticle, getCategories } from '@/api/article';

// 常量
const PAGE_SIZE = 20;

// 数据定义
const articles = ref([]);
const categories = ref([]);
const loading = ref(false);
const drawerVisible = ref(false);
const dialogType = ref('add');
const currentArticle = ref(null);
const currentPage = ref(1);
const totalArticles = ref(0);

const searchForm = ref({
  tag: '全部',
  search_title: '',
  dateRange: [],
});

// 计算属性
const drawerTitle = computed(() => {
  return dialogType.value === 'add' ? '添加文章' : '编辑文章';
});

// 方法定义
const fetchArticles = async () => {
  loading.value = true;
  try {
    const { data } = await getArticles(
      searchForm.value.tag,
      currentPage.value,
      searchForm.value.search_title,
      searchForm.value.dateRange?.[0],
      searchForm.value.dateRange?.[1]
    );
    if (data.code === 200) {
      articles.value = data.data;
      totalArticles.value = data.total;
    } else {
      ElMessage.error(data.message || '获取文章列表失败');
    }
  } catch (error) {
    ElMessage.error('获取文章列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

const fetchCategories = async () => {
  try {
    const { data } = await getCategories();
    if (data.code === 200) {
      categories.value = data.data;
    } else {
      ElMessage.error(data.message || '获取分类信息失败');
    }
  } catch (error) {
    ElMessage.error('获取分类信息失败：' + error.message);
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchArticles();
};

const handleReset = () => {
  searchForm.value.tag = '全部';
  searchForm.value.search_title = '';
  searchForm.value.dateRange = [];
  handleSearch();
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchArticles();
};

const showAddDrawer = () => {
  dialogType.value = 'add';
  drawerVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = 'edit';
  drawerVisible.value = true;
  currentArticle.value = { ...row };
  console.log('currentArticle',row);
  
};

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const { data } = await deleteArticle(row.id);
      if (data.code === 200) {
        ElMessage.success('删除成功');
        fetchArticles();
      } else {
        ElMessage.error(data.message || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败：' + error.message);
    }
  }).catch(() => { });
};

const closeDrawer = () => {
  drawerVisible.value = false;
  currentArticle.value = null;
};

const handleCancel = () => {
  closeDrawer();
};

// 生命周期钩子
onMounted(() => {
  fetchArticles();
  fetchCategories();
});
</script>

<style scoped>
.text-right {
  text-align: right;
}

.article-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>